#include "echoserver.hpp"
#include "logger.h"
#include "mytask.hpp"
#include <functional>
namespace moqi
{

EchoServer::EchoServer(const string & ip,
                       const unsigned int& port,
                       size_t threadnum,
                       size_t queSize)
:_pool(threadnum, queSize),
_server(port, ip)
{
#if 1
    using namespace std::placeholders;
    _server.setAllConnectionCallback(
                std::bind(&EchoServer::onConnection, this, _1),
                std::bind(&EchoServer::onMessage, this, _1),
                std::bind(&EchoServer::onClose, this, _1));
    //占位符的作用是？
#endif
}

EchoServer::~EchoServer()
{

}

void EchoServer::start()
{
    _pool.start();
#if 0
    using namespace std::placeholders;
    _server.setAllConnectionCallback(
                std::bind(&EchoServer::onConnection, this, _1),
                std::bind(&EchoServer::onMessage, this, _1),
                std::bind(&EchoServer::onClose, this, _1));
    //占位符的作用是？
#endif

    LOG_INFO(">>>>>>>>>>>>>>>>>>>>Server running<<<<<<<<<<<<<<<<<<<<");
    _server.start();
}

void EchoServer::stop()
{
    _server.stop();
    _pool.stop();

}

void EchoServer:: onConnection(TcpConnecitonPtr  con)
{
    LOG_INFO(con->status());
}

void EchoServer::onMessage(TcpConnecitonPtr  con)
{
    string msg = con->recv();//不能阻塞
    LOG_INFO(con->status() + " recv " + msg + " <<<");
    
    Mytask task(msg, con);//局部对象
    _pool.addTask(std::bind(&Mytask::process, task));//此处不能传递引用
}

void EchoServer::onClose(TcpConnecitonPtr  con)
{
     LOG_INFO(con->status()+" closed");
}




}//end of namespace moqi
